﻿using System;
using System.Drawing;
using System.IO;
using Sunny.UI;

namespace DevelopTool.Common
{
    /// <summary>
    /// 图片帮助类
    /// </summary>
    public class ImageHelper
    {

        /// <summary>
        /// 图片转为Base64文本
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public static string ConvertImageToBase64(Image image)
        {
            using(MemoryStream memoryStream = new MemoryStream())
            {
                // 将图片保存到内存流中  
                image.Save(memoryStream,image.RawFormat);
                byte[] imageBytes = memoryStream.ToArray();

                // 将字节数组转换为Base64字符串  
                return Convert.ToBase64String(imageBytes);
            }
        }


        /// <summary>
        /// Base64文本转为图片
        /// </summary>
        /// <param name="base64String"></param>
        /// <returns></returns>
        public static Image ConvertBase64ToImage(string base64String)
        {

            // 将Base64字符串解码为字节数组  
            byte[] imageBytes = Convert.FromBase64String(base64String);

            // 使用MemoryStream来保存字节数组  
            using(MemoryStream ms = new MemoryStream(imageBytes))
            {
                // 从MemoryStream创建Image对象  
                using(Image image = Image.FromStream(ms))
                {
                    string imagePath = Path.Combine(GlobalData.AppTempDirectory,Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".gif");

                    // 保存Image对象为GIF格式文件  
                    image.Save(imagePath,image.RawFormat);

                    return Image.FromFile(imagePath);
                }
            }
        }

        /// <summary>
        /// 判断文件是否是图片
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool IsImage(string path)
        {
            try
            {
                using(Image img = Image.FromFile(path))
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 获取打开文件对话框所有的图片类型过滤条件
        /// </summary>
        /// <returns>图片过滤字符串</returns>
        public static string GetImageFilter()
        {
            return ImageEx.GetImageFilter();
        }
    }
}
